package servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import service.AreaManager;
import service.impl.AreaManagerFactory;
import util.JSONUtil;

@WebServlet("/query")
public class QueryServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private AreaManager areaManager;
       
    public QueryServlet() {
        super();
        areaManager = AreaManagerFactory.getInstance();
    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String matchStr = request.getParameter("q");
		System.out.println(matchStr);
		if(matchStr!=null){
			List<String> list = areaManager.getMatchArea(matchStr);
			if(!list.isEmpty()){
				String str = JSONUtil.toJSON(list);
//				response.setCharacterEncoding("UTF-8"); //无法解决中文乱码，需要指定返回json及charset
				response.setContentType("application/json;charset=utf-8");
				response.getWriter().write(str);
				System.out.println(str);
			}
		}	
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
